package com.itheima.health.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.dto.SetmealDTO;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.SetmealMapper;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.aliyunoss.AliyunUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisConstant;
import com.itheima.health.vo.CheckGroupVO;
import com.itheima.health.vo.SetmealVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    //此方法用来添加表单信息
    @Override
    public Boolean saveOrUpdateSetmealInfo(SetmealDTO setmealDTO) {

        //获取此套餐的ID值id
        Integer id = setmealDTO.getId();

        //如果有ID,则会进行修改操作,修改之前先删除中间表中此套餐ID对应的检查组信息
        if (StringUtils.isNotBlank(String.valueOf(id))) {
            //根据检查组的ID删除中间表数据
            baseMapper.deleteSetmealAndCheckgroupInfoBySetmealId(id);
        }

        //执行检查组以及相关检查项的信息的添加或修改
        boolean flag = saveOrUpdate(setmealDTO);

        //当完成录入,自动生成主键
        Integer sid = setmealDTO.getId();

        //中间表数据添加插入
        //1.获取此套餐ID对应的检查组的ID数组
        Integer[] checkgroupIds = setmealDTO.getCheckgroupIds();

        //2.遍历添加到此检查组ID对应的检查项信息
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                baseMapper.addSetmealAndGroupIdInfo(sid, checkgroupId);
            }
        }


        //套餐修改或添加成功后，删除redis
        RedisUtil.removeKeys("findAllSetmeal");


        //当执行了此方法,就代表数据已经添加到数据库中,所以需要删除set集合中的数据
        //此时set集合中剩下的就是垃圾图片,需要根据这些垃圾图片到OSS中进行删除
        RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET, setmealDTO.getImg());
        //同时删除redis中的数据
        RedisUtil.delete(RedisConstant.SINGLE_PIC + setmealDTO.getImg());

        return flag;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //   select  * from xxx where is_delete = 0  and  xxx like ?
        //  条件构造出来   Wrapper对象
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<Setmeal>();
        Page<Setmeal> page = null;
        if (StringUtils.isBlank(queryPageBean.getQueryString())) {
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()));
        } else {
            queryWrapper.like("HELPCODE", queryPageBean.getQueryString());
            //   sql   + 追加  sql  where  name like  %?%
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()), queryWrapper);
        }
        PageResult result = new PageResult(page.getTotal(), page.getRecords());
        return result;
    }

    @Override
    public void clearOssImg() {
        //清理OSS的垃圾图片,由xxl-job调用

        //1.获取set集合中的所有数据
        Set<String> members = RedisUtil.getMembersOfSet(RedisConstant.ALL_SETMEAL_PIC_SET);

        if (members.size() != 0) {
            for (String uuidfilename : members) {
                //遍历图片,判断redis中是否存在
                boolean existsKey = RedisUtil.existsKey(RedisConstant.SINGLE_PIC + uuidfilename);
                if (existsKey == false) {
                    //表示redis中不存在,可以在OSS中删除,同时把set集合中的数据删除
                    AliyunUtils.deleteFile(uuidfilename);
                    System.out.println("OSS删除一次");
                    RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET, uuidfilename);
                    System.out.println("Set集合删除一次");
                }
            }
        }
    }

    @Override
    public SetmealVO findCheckgroupInfoBySetmealId(Integer id) {
        //查询所有检查组信息
        List<CheckGroupVO> checkGroupList = baseMapper.selectCheckgroupInfo();

        //根据sid查询对应的中间表的信息
        Integer[] checkgroupIds = baseMapper.findCheckgroupInfoBySetmealId(id);
        SetmealVO setmealVO = new SetmealVO();
        setmealVO.setCheckgroupIds(checkgroupIds);
        setmealVO.setCheckGroupList(checkGroupList);
        return setmealVO;
    }

    //根据ID查询套餐详情
    @Override
    public SetmealVO findSetmealDetailById(Integer id) {
        //经过三次查询得到一个SetmealVO,返回给前端

        //将从redis查到的集合转换成 java对象
        SetmealVO setmealVO = JSON.toJavaObject(RedisUtil.get("findSetmealDetailById"+id), SetmealVO.class);
        if (setmealVO == null) {
            //1.先根据套餐id查询套餐信息
            setmealVO = baseMapper.selectSetmealInfoById(id);
            //2.根据套餐id,查询对应检查组,放入SetmealVO的List<CheckGroupVO> checkGroupList集合中
            List<CheckGroupVO> checkGroupVOList = baseMapper.selectCheckgroupInfoById(id);
            //3.根据检查组id,查询对应检查项信息
            for (CheckGroupVO checkGroupVO : checkGroupVOList) {
                List<CheckItem> checkItemList = baseMapper.selectCheckitemInfoByGroupId(checkGroupVO.getId());
                checkGroupVO.setCheckItemList(checkItemList);
            }
            setmealVO.setCheckGroupList(checkGroupVOList);

            RedisUtil.set("findSetmealDetailById" + id, setmealVO);
            return setmealVO;
        }
        return setmealVO;
    }

    //注解
    @Override
    public Setmeal findSetmealInfoById(Integer id) {
        Setmeal setmeal = baseMapper.selectSetmealInfoById(id);
        return setmeal;
    }


    //查询所有套餐信息
    @Override
    public List<Setmeal> findAllSetmeal() {

        //直接从redis查 如果没有从数据库查 保存一份到redis
        List<Setmeal> setmealList = RedisUtil.get("findAllSetmeal");

        if (setmealList == null) {
            setmealList = baseMapper.findAllSetmeal();
            RedisUtil.set("findAllSetmeal", setmealList);
            return setmealList;
        }

        return setmealList;
    }


    @Override
    public List<Map> getHostSetmeal() {
        return baseMapper.getHostSetmeal();
    }
}
